package com.vogue.supplymall.account.shiro.filter;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vogue.supplymall.common.constant.ErrorCode;
import com.vogue.supplymall.common.domain.dto.UserInfo;

/**
 * 验证是否登录过的过滤器<br>
 * 
 * @author 崔岳
 *
 */
public class MallAuthenticationFilter extends BaseFilter {

	public static final Logger LOGGER_MALLAUTHENTICATIONFILTER = LoggerFactory.getLogger(MallAuthenticationFilter.class);
	
	/**
	 * 一次性登录允许的地址
	 */
	public static final List<String> effectiveUrl = new ArrayList<>();
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		HttpServletRequest httpRequest = WebUtils.toHttp(request);
		//OPTIONS 实际是不做业务处理的一次试探访问，因此不对此请求进行业务限制
//		if("OPTIONS".equals(httpRequest.getMethod())) {
//			return true;
//		}
		String url = httpRequest.getRequestURL().toString();
		url = url.substring(url.indexOf("/suppliermall"));
		if (isLoginRequest(request, response)) {
			return true;
		} else {
			Subject subject = getSubject(request, response);
			Object obj = subject.getPrincipal();
			if(obj != null) {
				if(((UserInfo)obj).isOnceFlag()) {
					return effectiveUrl.contains(url);
				}else {
					return true;
				}
			}else {
				return false;
			}
		}
	}

	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		ajaxResponse(request, response, ErrorCode.NeedCredentials.getCode());
		LOGGER_MALLAUTHENTICATIONFILTER.debug("-------403-------");
		return false;
	}

	public List<String> getEffectiveUrl() {
		return effectiveUrl;
	}
	
	@SuppressWarnings("static-access")
	public void setEffectiveUrl(List<String> effectiveUrl) {
		this.effectiveUrl.addAll(effectiveUrl);
	}
	
}
